使用binary search能讓時間複雜度在:O(log(min(m,n))),透過low & high管理上下限,找出mid
ref:https://leetcode.com/problems/median-of-two-sorted-arrays/solutions/4070371/94-96-binary-search-with-partitioning-o-log-min-m-n/?envType=daily-question&envId=2023-09-21
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if(nums1.size() > nums2.size()){
swap(nums1, nums2);
}
int m = nums1.size();
int n = nums2.size();
int low = 0, high = m;
while(low <= high){
int pX = (low + high) / 2;
int pY = (m + n + 1) / 2 - pX;
int maxX = (pX == 0) ? INT_MIN : nums1[pX - 1];
int maxY = (pY == 0) ? INT_MIN : nums2[pY - 1];
int minX = (pX == m) ? INT_MAX : nums1[pX];
int minY = (pY == n) ? INT_MAX : nums2[pY];
if(maxX <= minY && maxY <= minX){
if((m + n) % 2 == 0){
return (max(maxX, maxY) + min(minX, minY)) / 2.0;
}
else {
return max(maxX, maxY);
}
}
else if(maxX > minY){
high = pX - 1;
}
else{
low = pX + 1;
}
}
return 0;
}
};